﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YNCNumberSys.db;

namespace YNCNumberSys.DbDal
{
    public class StatusDal
    {
        private CommandManager commandManager = new CommandManager();
        private ConnectionManager connectionManager = new ConnectionManager();
        public System.Data.DataTable IsLock()
        {
            string sql = string.Format(@"SELECT [user] ,[LockTime] FROM [YNCNumberSys].[dbo].[LockCurrentUser]");
            return commandManager.ExecuteNonQuery(connectionManager.getConnection(), sql, @"状态");    
        }
        /// <summary>
        /// 是否被占用。
        /// </summary>
        /// <returns>ok 成功;被他人占用 err</returns>
        public string IsLock(string usm)
        {
            string sql = @"SELECT [user]
                                  ,[LockTime]
                              FROM [dbo].[LockCurrentUser]";
            DataTable dt = commandManager.ExecuteNonQuery(connectionManager.getConnection(), sql, "lock");
            if (dt.Rows.Count == 1)
            {
                if (usm == (string)dt.Rows[0]["user"])
                    return @"ok";
                else
                {
                    string err = string.Format("提示：{0}{1}正在申请图号，请稍等几秒后再试", dt.Rows[0]["LockTime"], dt.Rows[0]["user"]);
                    return err;
                }
            }
            else
                return @"ok";
        }
        /// <summary>
        /// 加锁。
        /// </summary>
        /// <param name="usm">操作的用户名。</param>
        /// <returns></returns>
        public DataTable Lock(string usm)
        {
            string sql = string.Format(@"exec [dbo].[YNC_LOCK] '{0}'", usm);
            return commandManager.ExecuteNonQuery(connectionManager.getConnection(), sql, @"加锁");
        }
        public DataTable UnLock(string usm)
        {
            string sql = string.Format(@"exec [dbo].[YNC_UNLOCK] '{0}'", usm);
            return commandManager.ExecuteNonQuery(connectionManager.getConnection(), sql, @"解锁");
        }
    }
}
